<template>
    <div class="chat-input">
      <div class="file-previews" v-if="files.length">
        <div v-for="(file, index) in files" :key="file.id" class="file-item">
          <span class="file-name">{{ file.name }}</span>
          <button @click="removeFile(index)">×</button>
        </div>
      </div>
  
      <div class="input-area">
        <textarea
          v-model="inputText"
          @keydown.enter.exact.prevent="send"
          placeholder="Type your message..."
          :disabled="isSending"
        ></textarea>
        <input
          type="file"
          multiple
          @change="handleFile"
          ref="fileInput"
        />
        <button @click="send" :disabled="!canSend">
          {{ isSending ? 'Sending...' : 'Send' }}
        </button>
      </div>
    </div>
  </template>
  
  <script lang="ts">
  import { Component, Vue } from 'vue-property-decorator'
  import { namespace } from 'vuex-class'
  import { uploadFile } from '@/api/dify'
  import { SendMessageParams } from '@/types/dify'
  
  const difyChat = namespace('difyChat')
  
  @Component
  export default class ChatInput extends Vue {
    @difyChat.State isSending!: boolean
    @difyChat.State userId!: string
    @difyChat.Action sendMessage!: (params: SendMessageParams) => Promise<void>
  
    inputText = ''
    files: File[] = []
    uploadProgress: number[] = []
  
    get canSend(): boolean {
      return !this.isSending && (!!this.inputText.trim() || this.files.length > 0)
    }
  
    async send() {
      if (!this.canSend) return
  
      try {
        const fileIds = await Promise.all(
          this.files.map(file => uploadFile(file, this.userId))
       )
        await this.sendMessage({
          query: this.inputText,
          files: fileIds,
          conversation_id: this.$store.state.difyChat.activeConversation?.id
        })
        this.inputText = ''
        this.files = []
      } catch (error) {
        console.error('Failed to send message:', error)
      }
    }
  
    handleFile(event: Event) {
      const input = event.target as HTMLInputElement
      if (input.files) {
        this.files = Array.from(input.files)
      }
    }
  
    removeFile(index: number) {
      this.files.splice(index, 1)
    }
  }
  </script>
  
  <style scoped>
  .chat-input {
    padding: 1rem;
    border-top: 1px solid #eee;
  }
  
  .input-area {
    display: flex;
    gap: 0.5rem;
  }
  
  textarea {
    flex: 1;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    min-height: 40px;
  }
  </style>